function bind_all() {
	Auth.init()
	EmpAuth.init()
	load_app('search')
}

// unused code
function bind_enter(t, f) {
	t.onkeypress = function (e) {
		var e = e ? e : (event ? event : null)
		var node = e.target ? 
			e.target : (e.srcElement ? e.srcElement : null)
		if (e.keyCode == 13 && node.type=="text") return f()
	}
}

function build_app_forms(app, background) {
	var forms = $$(app, 'form')
	for (var i = 0; i < forms.length; i++) {
		forms[i].submit = forms[i].onsubmit = function() {
			var params = {}
			function add_param(e) {
				if (e.hasAttribute('name'))
					params[e.name] = (e.type == 'password' ? 
						Base64.encode(e.value) : e.value)
				else if (e.hasChildNodes())
					for (var c = e.firstChild; 
							c != null; c = c.nextSibling)
						if (c.nodeType == Node.ELEMENT_NODE)
							add_param(c)
			}
			add_param(this)
			background ? 
				call_app_at(this.action, params) : 
				load_app_from(this.action, params)
			return false
		}
	}
}

function load_app(name, params) {
	load_app_from("app/" + name + ".php", params)
}

function load_app_from(uri, params) {
	call_app_at(uri, params, 
		function(xml) {
			$('nav').textContent = "You are here: " + 
				$$(xml ,'nav')[0].textContent
			var screen = $$(xml, 'app')[0]
			$('app').innerHTML = ""
			$add($('app'), as_array
				(document.importNode(screen, true).childNodes))
			build_app_forms($('app'))
		}, 
		function(xml) {
			$('nav').textContent = xml.documentElement.textContent || 
				"Error: Failed to establish the connection. "
		})
}

function call_app(name, params, success, fail) {
	call_app_at("app/" + name + ".php", params, success, 
		fail || function(xml) {
			$('nav').textContent = xml.documentElement.textContent || 
				"Operation failed. Bad response. "
		})
}

function call_app_at(uri, params, success, fail, method) {
	var xhr = new Xhr(uri, params || '', method)
	xhr.onready = function() { success && success(xhr.getXML()) }
	xhr.onfail = function() { fail && fail(xhr.getXML()) }
	xhr.start()
}

var Auth = {
	ui : {
		login_box : make_login(), 
		welcome_box : make_welcome(), 
		reset : function() {
			$('log_fail').textContent = ""
			$('upass').value = ""
			$('upass').focus()
		}
	}, 
	init : function() {
		$$(Auth.ui.login_box, 'form')[0].onsubmit = Auth.login
		if (Auth.mod.online()) {
			$insert($('sidebar'), Auth.ui.welcome_box)
			$$(Auth.ui.welcome_box, 'p')[1].textContent = 
				"You are logged in as " + Auth.mod.username()
		} else 
			$insert($('sidebar'), Auth.ui.login_box)
	}, 
	mod : new function() {
		this.online = function() { return !!this.username() }
		this.username = function() { return get_cookie('uname') }
		this.login = function(success, fail) {
			var mod = this
			var xhr = new Xhr(document.forms[0].action, 
					{uid: $('uid').value, upass: 
					Base64.encode($('upass').value)}, 'POST')
			xhr.onready = function() {
				if (mod.username())
					success()
				else fail()
			}
			xhr.onfail = function() {
				$('log_fail').textContent = "Server is down. "
			}
			xhr.start()
		}
		this.logout = function() {
			var xhr = new Xhr('auth.php', 'logout=yes', 'POST')
			xhr.start()
		}
	}(), 
	login : function() {
		Auth.mod.login(function() {
				$replace(Auth.ui.login_box, Auth.ui.welcome_box)
				$$(Auth.ui.welcome_box, 'p')[1].textContent = 
					Auth.mod.username() + 
					", welcome to Dummy Autos. "
			}, 
			function() {
				Auth.ui.reset()
				$('log_fail').textContent = "Failed to login. "
			})
		return false
	}, 
	logout : function() {
		Auth.mod.logout()
		$replace(Auth.ui.welcome_box, Auth.ui.login_box)
		Auth.ui.reset()
		load_app('search')
	}
}

var EmpAuth = new function() {
	var entry = make_emp_login()
	var switcher = $make('div', '', 'expender', 'employee &raquo;')
	var form = $$(entry, 'form')[0]

	switcher.onclick = function() {
		entry.style.display = entry.style.display ? '' : 'none'
		$('eid').focus()
	}
	this.init = function() {
		$add($('sidebar'), switcher)
		$add($('sidebar'), entry)
		switcher.onclick()
		form.onsubmit = this.login
	}
	this.login = function(){
		var xhr = new Xhr(form.action, 
				{eid: $('eid').value, epass: 
				Base64.encode($('epass').value), 
				role: 'employee'}, 'POST')
		xhr.onready = function() {
			if (get_cookie('ename')) {
				$('sidebar').innerHTML = ''
				$add($('sidebar'), make_emp_tools())
				load_app('schedule')
			} else location.reload()
		}
		xhr.onfail = function() {
			$('log_fail').textContent = "Server is down. "
		}
		xhr.start()
		return false
	}
	this.logout = function() {
		var xhr = new Xhr('auth.php', 'role=employee&logout=yes', 'POST')
		xhr.onfail = xhr.onready = function() {
			document.cookie = ""
			location.reload()
		}
		xhr.start()
	}
}

function make_form(action, method) {
	return $make('form', {'action': action, 'method': method})
}

function make_login() {
	return $add($make('div', 'login', 'sidetool'), 
		$add($make('p'), 
			$make('span', '', 'selected', "Log In"), 
			$add($make('span', 'signup_tab', 'deselected'), 
				$make('a', {href: 
					"javascript:load_app('register')"}, "Sign Up"))), 
		$add($make('div'), 
			$add(make_form('auth.php', 'post'), 
				$add($make('div'), 
					$add($make('label', '', '', "User ID: "), 
						$make('input', {id: 'uid', type: 'text'}))), 
				$add($make('div'), 
					$add($make('label', '', '', "Password: "), 
						$make('input', {id: 'upass', type: 'password'}))), 
				$add($make('div'), 
					$make('span', 'log_fail'), 
					$make('input', {class: 'submit', 
						type: 'submit', value: "Log in"})))))
}

function make_welcome() {
	return $add($make('div', 'welcome', 'sidetool'), 
		$add($make('p'), 
			$make('span', '', 'selected', "Info")), 
		$add($make('div'), 
			$make('p'), 
			$add($make('p', '', '', 'To log out, '), $make('a', 
					{href: "javascript:Auth.logout()"}, 'click here. '))))
}

function make_emp_login() {
	return $add($make('div', 'emp_login', 'sidetool'), 
		$add($make('p'), 
			$make('span', '', '', "Employee Entry")), 
		$add($make('div'), 
			$add(make_form('auth.php', 'post'), 
				$add($make('div'), 
					$add($make('label', '', '', "ID: "), 
						$make('input', {id: 'eid', type: 'text'}))), 
				$add($make('div'), 
					$add($make('label', '', '', "Password: "), 
						$make('input', 
							{id: 'epass', type: 'password'}))), 
				$add($make('div'), 
					$make('input', {class: 'submit', 
						type: 'submit', value: "Log in"})))))
}

function make_emp_tools() {
	return $add($make('div', 'toolbar', 'sidetool'), 
		$add($make('p'), 
			$make('span', '', 'selected', "Management")), 
		$add($make('div'), 
			make_app_link('manager', 'Add Cars'),
			make_app_link('salesperson', 'Update Sale'),
			make_app_link('technician', 'Update Maintenance'),
			make_app_link('schedule', 'View Schedule'),
			$make('a', {href: "javascript:EmpAuth.logout()"}, 'Logout')))
}

function make_app_link(name, description) {
	return $make('a', 
			{href: "javascript:load_app('" + name + "')"}, description)
}

function get_checked(e) {
	var ls = $$(e, 'input')
	for (var i = 0; i < ls.length; i++)
		if (ls[i].checked)
			return ls[i].value
	return null
}

window.onload = bind_all
